//
//  YYOauthViewController.swift
//  YYWeibo
//
//  Created by strongwallyi on 15/12/29.
//  Copyright © 2015年 strongwallyi. All rights reserved.
//

import UIKit
import SVProgressHUD

var WB_APPKEY = "3075287458"
var WB_REDIRECTURI = "http://www.itheima.com/"
var WB_SECRET = "3c6247d70c9297db694e6ce7e72bad6c"

class YYOauthViewController: UIViewController, UIWebViewDelegate {
    
    override func loadView() {
        view = webView
        setupUI()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECTURI)"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
//        print(request)
        webView.loadRequest(request)
    }
    
    //设置 UI
    private func setupUI(){
        navigationItem.title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target:  self, action: "autoFill")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target:  self, action: "close")
    }
    
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充的方法
    @objc private func autoFill(){
        let jsString = "document.getElementById('userId').value='yohtr35601@163.com';document.getElementById('passwd').value='qw1987';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //懒加载 webview 控件
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
    
}

////通过code获取 accesstoken
//extension YYOauthViewController{
//    
//    func loadAccessToken(code:String){
//        //请求地址
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        //请求参数
//        let parameter = [
//            "client_id":WB_APPKEY,
//            "client_secret":WB_SECRET,
//            "grant_type":"authorization_code",
//            "code":code,
//            "redirect_uri":WB_REDIRECTURI
//        ]
//        
//        //发送请求
//        YYNetworkTools.sharedTools.request(YYRequestMethod.POST, urlString: urlString, parameters: parameter) { (response, error) -> () in
//            if error != nil{
//                print(error)
//                
//                return
//            }
//            
//            //判断返回的是不是字典
//            guard let dict = response as? [String: AnyObject] else{
//                print("返回的不是字典")
//                return
//            }
//            
//            //字典转模型
//            let account = YYUserAccount(dict: dict)
////            print(account)
//            //加载用户的个人信息
//            self.loadUserAccount(account)
//        }
//    }
//
//    //如果上面的代码执行到这里,那么就说明参数一定不为 nil
//    //利用 accesstoken 来获取用户信息
//    func loadUserAccount(account: YYUserAccount){
//        //请求地址
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        //请求参数
//        let params = [
//            "access_token":account.access_token!,
//            "uid":account.uid!
//        ]
//        
//        //请求个人信息
//        YYNetworkTools.sharedTools.request(YYRequestMethod.GET, urlString: urlString, parameters: params) { (response, error) -> () in
//            if error != nil{
//                print(error)
//                return
//            }
//            
//            //取到用户的昵称和头像
//            guard let dict = response as? [String: AnyObject] else{
//                return
//            }
//            
//            //设置用户的头像和昵称
//            account.avatar_large = dict["avatar_large"] as? String
//            account.screen_name = dict["screen_name"] as? String
//            
//            print(account)
//            
//            //保存登陆完成的信息
//            let file = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("useraccount.archive")
//            print(file)
//            //归档
//            NSKeyedArchiver.archiveRootObject(account, toFile: file)
//            
//        }
//    }
//}

//MARK:UIWebView 的代理方法
//获取到 code
extension YYOauthViewController{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else{
            return true
        }
        
        if !urlString.hasPrefix(WB_REDIRECTURI){
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code="){
            print(query)
            let code = query.substringFromIndex("code=".endIndex)
//            print("code",code)
            YYUserAccountViewModel.sharedViewModel.loadAccessToken(code, compeleted: { (isSuccess) -> () in
                if isSuccess {
//                    print("请求完成要做的事情,切换控制器")
                    SVProgressHUD.dismiss()
                    //先让弹窗消失再切换控制器
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(YYSwitchRootViewControllerNotification, object: self)
                    })
                    
                }else{
                    print("请求失败")
                }
            })
    
        }else{
            //用户关闭界面
            close()
        }
        
        return false
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}




